<template>
  <a-tabs v-model:activeKey="activeKey">
    <a-tab-pane key="baseInfo" tab="基本信息">
      <a-form
        ref="deptRef"
        :label-col="{ span: 8 }"
        :wrapper-col="{ span: 16 }"
        :model="deptInfo"
      >
        <a-row :gutter="24" style="margin-left: 0px;margin-right: 0px;">
          <a-col :span="12">
              <a-form-item  label="部门名称" name="name" 
                  :rules="[{ required: true, message: '请输入部门名称!' }]">
                  <a-input v-model:value="deptInfo.name"></a-input>
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="部门编码" name="code" 
                  :rules="[{ required: true, message: '请输入部门编码!' }]">
                  <a-input v-model:value="deptInfo.code"></a-input>
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="部门简称" name="shortName" >
                  <a-input v-model:value="deptInfo.shortName"></a-input>
              </a-form-item>
          </a-col>
          <!-- <a-col :span="12">
              <a-form-item  label="所属机构" name="orgId">
                  <a-tree-select
                      v-model:value="deptInfo.orgId"
                      style="width: 100%"
                      :tree-data="orgTree"
                      allow-clear
                      placeholder="请选择"
                      tree-node-filter-prop="label"
                  />
              </a-form-item>
          </a-col> -->
          <a-col :span="12">
              <a-form-item  label="上级部门" name="parentId">
                  <a-tree-select
                      v-model:value="deptInfo.parentId"
                      style="width: 100%"
                      :tree-data="deptTree"
                      allow-clear
                      placeholder="请选择"
                      tree-node-filter-prop="label"
                  />
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="部门负责人" name="deptLeader">
                  <div style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
                      <a-space>
                          <div style="overflow: auto;" class="tagboxs">
                              <a-tag closable @close="handleClose()" v-for="tag in leaderTags" :key="tag">
                                  {{ tag.NAME }}
                              </a-tag>
                          </div>
                      </a-space>
                      <n-button style="margin-left: auto;" size="small" secondary type="info" @click="openLeaderModal">
                          <template #icon>
                              <n-icon><svg-icon name="touxiang" size="18" /></n-icon>
                          </template>请选择
                      </n-button>
                  </div>
                  <a-input v-model:value="deptInfo.deptLeader" hidden></a-input>
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="上级领导" name="parentLeader">
                  <div style="border: 1px solid #e6e8eb;display: flex;justify-content: space-between;align-items: center;">
                      <a-space>
                          <div style="overflow: auto;" class="tagboxs">
                              <a-tag closable @close="handleParentClose()" v-for="tag in parentLeaderTags" :key="tag">
                                  {{ tag.NAME }}
                              </a-tag>
                          </div>
                      </a-space>
                      <n-button style="margin-left: auto;" size="small" secondary type="info" @click="openParentLeaderModal">
                          <template #icon>
                              <n-icon><svg-icon name="touxiang" size="18" /></n-icon>
                          </template>请选择
                      </n-button>
                  </div>
                  <a-input v-model:value="deptInfo.parentLeader" hidden></a-input>
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="部门电话" name="phoneNumber">
                  <a-input type="tel" v-model:value="deptInfo.phoneNumber"></a-input>
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="邮寄地址" name="postAddress">
                <a-input type="tel" v-model:value="deptInfo.postAddress"></a-input>
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="是否启用" name="IS_ENABLED">
                  <a-radio-group v-model:value="deptInfo.IS_ENABLED">
                      <a-radio :value=0>不启用</a-radio>
                      <a-radio :value=1>启用</a-radio>
                  </a-radio-group>
              </a-form-item>
          </a-col>
          <a-col :span="12">
              <a-form-item  label="是否与业务相关" name="IS_BUSINESS">
                  <a-radio-group v-model:value="deptInfo.IS_BUSINESS">
                      <a-radio :value=0>否</a-radio>
                      <a-radio :value=1>是</a-radio>
                  </a-radio-group>
              </a-form-item>
          </a-col>
          <a-col :span="12" >
              <a-form-item label="部门标签" name="orgTags">
                  <a-input v-model:value="deptInfo.orgTags"></a-input>
              </a-form-item>
          </a-col>
          <a-col :span="12" >
              <a-form-item  label="排序号" name="orgSort">
                  <a-input-number v-model:value="deptInfo.orgSort"></a-input-number>
              </a-form-item>
          </a-col>
          <a-col :span="24" >
              <a-form-item  :label-col="{ span: 4 }"
              :wrapper-col="{ span: 20 }"  label="备注" name="remark">
                  <a-textarea v-model:value="deptInfo.remark"></a-textarea>
              </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-tab-pane>
    <a-tab-pane v-if="deptInfo.id!==''&&deptInfo.id!==undefined" key="deptStation" tab="部门岗位" style="height: 100%;">
      <StationTable :data-request="getDeptStations" :columns="postsColumns" >
      </StationTable>
    </a-tab-pane>
    <a-tab-pane v-if="deptInfo.id!==''&&deptInfo.id!==undefined" key="deptUsers" tab="部门人员" style="height: 100%;">
      <UserTable :data-request="getDeptUsers" :columns="userColumns" >
      </UserTable>
    </a-tab-pane>
  </a-tabs>
</template>


<script lang="tsx" setup>
  import { onMounted, reactive,h, ref, watch ,defineComponent,unref} from 'vue';
  import type { FormInstance } from 'ant-design-vue';
  import { blankData } from '@/views/organization/departments/formSchemas';
  import { useModal } from '@/hooks/useModal/useModal';
  import userSingle from '@/components/system/orgUserSingle/userSingle.vue';
  import { useTable } from '@/components/core/dynamic-table';
  import { getUserByDepartId } from '@/api/system/user';
  import { gePostList } from '@/api/organization/station/station';
  import type { LoadDataParams } from '@/components/core/dynamic-table';

  interface Props {
    defaultData?: any;
  }
  defineComponent({
        userSingle,
  })

  const props = withDefaults(defineProps<Props>(), {
    defaultData: {
      orgTree:[],
      deptTree:[],
      deptItem:{...blankData},
    },
  });

  defineOptions({
    name: 'DeptDetail',
  });
  const [ModalRender, modalRef] = useModal()
  //form
  const deptRef = ref<FormInstance>();
  //选择人ref
  const userSingleRef = ref<FormInstance>();
  //机构信息
  const deptInfo = reactive(props.defaultData.deptItem);
  //机构树
  const orgTree=reactive(props.defaultData.orgTree);
  //部门树
  const deptTree=reactive(props.defaultData.deptTree);
  const leaderTags=ref<any>([]);
  const parentLeaderTags=ref<any>([]);
  const activeKey=ref("baseInfo");
  //部门人员列表
  const userList=ref<any>([]);
  //部门岗位列表
  const stationList=ref<any>([]);

  const loadTagData=()=>{
    if(deptInfo.deptLeader!==''&&deptInfo.deptLeaderName!==''){
      const tag={
        NO:deptInfo.deptLeader,
        NAME:deptInfo.deptLeaderName,
        ORG_TYPE:'user'
      }
      leaderTags.value.push(tag);
    }
    if(deptInfo.parentLeader!==''&&deptInfo.parentLeaderName!==''){
      const tag={
        NO:deptInfo.parentLeader,
        NAME:deptInfo.parentLeaderName,
        ORG_TYPE:'user'
      }
      parentLeaderTags.value.push(tag);
    }
  };
  const getDeptUsers = async (params: LoadDataParams) => {
    const data = await getUserByDepartId({
      departid: deptInfo.id.length ? deptInfo.id : '',
    });
    return {
      list: data?.result || [],
      pagination: {
        total: data.total,
        size: params.limit,
        page: params.pageNum,
      },
    } as API.TableListResult;
  };
  const getDeptStations = async (params: LoadDataParams) => {
      const data = await gePostList({
        ...params,
        orgId: deptInfo.id.length ? deptInfo.id : '',
      });
      return {
        list: data?.rows || [],
        pagination: {
          total: data.total,
          size: params.limit,
          page: params.pageNum,
        },
      } as API.TableListResult;
    };
  onMounted(() => {
    loadTagData();
  });
  const editDrawerBindValue = reactive({
    defaultSelectData: []
  });
  const openLeaderModal = async()=>{
    editDrawerBindValue.defaultSelectData=leaderTags.value;
    ModalRender.show({
      title: '选择机构领导',
      width: '70%',
      // 是否显示右上角确定取消
      defaultExtra: true,
      destroyOnClose: true,
      content: () => {
        return <userSingle  ref={userSingleRef} defaultData={unref(editDrawerBindValue)}></userSingle>;
      },
      // 确定方法执行
      onOk: async () => {
        const res = await userSingleRef.value?.handleSubmit();
        if (!res) return;
        leaderTags.value=[];
        leaderTags.value.push(res);
        deptInfo.deptLeader=res.NO;
      },
    });
  };
  const openParentLeaderModal = async()=>{
    ModalRender.show({
      title: '选择上级机构领导',
      width: '70%',
      // 是否显示右上角确定取消
      defaultExtra: true,
      destroyOnClose: true,
      content: () => {
        return <userSingle  ref={userSingleRef} defaultData={unref(editDrawerBindValue)}></userSingle>;
      },
      // 确定方法执行
      onOk: async () => {
        const res = await userSingleRef.value?.handleSubmit();
        if (!res) return;
          parentLeaderTags.value=[];
          parentLeaderTags.value.push(res);
          deptInfo.parentLeader=res.NO;
      },
    });
  };
  const [UserTable] = useTable({
        size: 'small',
        rowKey: 'userAccount',
        bordered: true,
        showIndex: true,
        search: false,
        showToolBar: false,
    });
    const userColumns = [
    {
      title: '人员姓名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '登录账号',
      dataIndex: 'userAccount',
      align: 'center',
    }
  ];
  const [StationTable] = useTable({
        size: 'small',
        rowKey: 'code',
        bordered: true,
        showIndex: true,
        search: false,
        showToolBar: false,
    });
    const postsColumns = [
    {
      title: '岗位姓名',
      dataIndex: 'name',
      align: 'center',
    },
    {
      title: '岗位编码',
      dataIndex: 'code',
      align: 'center',
    }
  ];
  const handleClose=()=>{
    leaderTags.value=[];
    deptInfo.leader="";
  }
  const handleParentClose=()=>{
    parentLeaderTags.value=[];
    deptInfo.parentLeader="";
  }
  const onSubMit = () => {
    return [deptInfo,deptRef];
  };

  defineExpose({
    handleSubmit: onSubMit,
  });

  watch(
    () => props.defaultData,
    async (newVal) => {
      if (!newVal) return;
      if (newVal.id) {
      }
    },
  );

  onMounted(() => {
    // schemaFormRef.value?.setFieldsValue({
    //   ...props.defaultData,
    // });
    // props.updateSchema.length && schemaFormRef.value?.updateSchema(props.updateSchema);
  });
</script>
